/*
 * Created on 2006-6-26
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.powerunion.datacollection.report.excelreport.datasource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.powerunion.datacollection.report.excelreport.config.DataSourceConfig;
import com.powerunion.datacollection.report.excelreport.util.HelpTools;


/**
 * 数据库数据自动检索数据源对象. 该数据源可以在配置文件中配置
 * SQL检索语句, 数据源会自动根据该SQL从数据库检索数据.
 * @author juny
 */
public abstract class DBDataSource extends BaseDataSource {
    public DBDataSource(){
        super();
    }
    
    public DBDataSource(DataSourceConfig config, String name){
        super(config, name);
    }
    
    /*
     *  (non-Javadoc)
     * @see excel.report.datasource.BaseDataSource#query(java.util.Map)
     */
    public int query(Map param) throws Exception {
        return IDataSource.QUERY_FAILURE;
    }
    
    /**
     * 组合SQL语句.调用该函数可以取得用户配置的SQL语句，如果SQL语句中有相应的参数的话，
     * 其参数值也已经被组合到SQL语句中。
     * @return
     */
    protected String getSql() {
        List pms = getConfig().getParams();
        String templetSql = getConfig().getSQL();
        String value = null;
        String sql = null;
        Map param = getParams();
        
        if(null != dbQueryListener){
            sql = this.dbQueryListener.getSql(pms, param);
        }
        
        if(sql == null || sql.trim().length() <=0 ){
            sql = templetSql;
	        for (int i = 0; i < pms.size(); i++) {
	            String key = (String) pms.get(i);
	            value = param.get(key).toString();
	            sql = HelpTools.replace(sql, key, value);
	        }
        }
        return sql;
    }
    
    private IDBDataSourceQueryListener dbQueryListener;
    /**
     * 给一个数据库类型数据源设置查询监听器
     * @param listener
     */
    public void setDBDataSourceQueryListener(IDBDataSourceQueryListener listener){
        this.dbQueryListener = listener;
    }
}
